package com.mashibing.apidriver.interceptor;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.mashibing.constant.TokenTypeConstant;
import org.mashibing.dto.ResponseResult;
import org.mashibing.dto.TokenResult;
import org.mashibing.util.JwtUtils;
import org.mashibing.util.RedisPrefixUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author:
 * @create: 2024/3/28 15:52
 * @description: JWT拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String GENERIC_TOKEN_INVALID_MSG = "token invalid";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader(AUTHORIZATION_HEADER);
        TokenResult tokenResult = null;
        if (token == null) {
            sendUnauthorizedResponse(response, "Missing or invalid Authorization header");
            return false;
        }
        try {
            // 解析token
            tokenResult = JwtUtils.pareToken(token);
        } catch (Exception e) {
            sendUnauthorizedResponse(response, GENERIC_TOKEN_INVALID_MSG);
            return false;
        }

        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();
        // 生成redisKey
        String tokenKey = RedisPrefixUtil.generatorTokenKey(phone, identity, TokenTypeConstant.ACCESS_TOKEN_TYPE);
        // 查找redis是否有该token
        String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);

        if (StringUtils.isBlank(tokenRedis) || !StringUtils.equals(token, tokenRedis)) {
            sendUnauthorizedResponse(response, GENERIC_TOKEN_INVALID_MSG);
            return false;
        }
        return true;
    }

    /**
     * 错误信息返回
     */
    private void sendUnauthorizedResponse(HttpServletResponse response, String errorMessage) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json");
        response.getWriter().write(new ObjectMapper().writeValueAsString(ResponseResult.fail(errorMessage)));
    }
}
